<?php
class User extends CI_Controller {
	function __construct() {
		parent::__construct ();
		$this->load->helper ( 'url' );
		$this->load->library ( 'form_validation' );
	}
	
	function index() {
		redirect ( base_url () . 'user/center' );
	}
	
	function center() {
		$this->load->model ( 'Muser' );
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		if ($data ['uid']) {
			$data ['name'] = $this->session->userdata ( 'uname' );
			$this->load->view ( 'user_center', $data );
		} else {
			$data ['msg'] = 'login';
			$data ['url'] = base_url () . 'user/login';
			$this->load->view ( 'redirect', $data );
		}
	}
	
	function login() {
		$this->load->model ( 'Muser' );
		$this->load->helper ( 'string' );
		$this->load->helper ( 'form' );
		$this->load->model ( 'Mabout' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['msg'] = '';
		
		$this->form_validation->set_rules ( 'email', '邮箱', 'trim|required|valid_email|max_length[40]' );
		$this->form_validation->set_rules ( 'password', '登录密码', 'trim|required|min_length[6]|max_length[15]' );
		$this->form_validation->set_rules ( 'test', '验证码', 'trim|required|callback_checkCaptchaCB' );
		if ($this->form_validation->run () == FALSE) {
			if ($data ['uid']) {
				redirect ( base_url () . 'home' );
			} else {
				$data ['img'] = $this->getCaptcha ();
				$data ['form'] = array ('id' => 'loginForm' );
				$this->load->view ( 'user_login', $data );
			}
		} else {
			$queryL = $this->Muser->getUserIdbyEmailPwd ( $this->input->post ( 'email' ), md5 ( $this->input->post ( 'password' ) ), $this->input->ip_address () );
			if ($queryL) {
				if ($queryL ['activation'] == '#') {
					$this->session->set_userdata ( 'uid', $queryL ['id'] );
					$this->session->set_userdata ( 'uname', $queryL ['name'] );
					redirect ( base_url () . 'user/center' );
				} else
					redirect ( base_url () . 'user/waitActivation/' . $queryL ['id'] );
			} else {
				$data ['msg'] = '邮箱或密码错误';
				$data ['img'] = $this->getCaptcha ();
				$data ['form'] = array ('id' => 'loginForm' );
				$this->load->view ( 'user_login', $data );
			}
		}
	}
	
	function forget() {
		$this->load->helper ( 'form' );
		$this->load->model ( 'Muser' );
		$this->load->helper ( 'string' );
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$this->form_validation->set_rules ( 'email', '邮箱', 'trim|required|valid_email|max_length[40]|callback_checkEmail2CB' );
		$this->form_validation->set_rules ( 'test', '验证码', 'trim|required|callback_checkCaptchaCB' );
		if ($this->form_validation->run () == FALSE) {
			$data ['img'] = $this->getCaptcha ();
			$data ['form'] = array ('id' => 'forgetForm' );
			$this->load->view ( 'user_forget', $data );
		} else {
			$str = random_string ( 'alnum', 15 );
			if ($this->Muser->updateReset ( $str, $this->input->post ( 'email' ) )) {
				$user = $this->Muser->getIdNamebyEmail ( $this->input->post ( 'email' ) );
				$str = $user ['id'] . '_' . $str;
				$resetMsg = "
							<p>亲爱的纽斯达用户，您好！</p>
							<p>&nbsp;</p>
							<p>请点击下面的链接地址，重新设置纽斯达账号密码：</p>
							<p><a href=\"" . base_url () . "user/resetPwd/$str/\">" . base_url () . "user/resetPwd/$str/</a></p>
							<p>（如果您无法点击此链接，请将上面的链接地址复制到您的浏览器地址栏中，打开页面即可）</p>
							<p>&nbsp;</p>
							<p>这是一封系统邮件，请勿回复</p>
							<p>&nbsp;</p>
							<p>上海纽斯达科技有限公司</p>
							<p>http://www.nsdkj.com.cn</p>
							<p>客服信箱：nsdkj@nsdkj.com.cn</p>
							<p>热线电话：021-63831111</p>
							";
				error_reporting ( E_STRICT );
				date_default_timezone_set ( "Asia/Shanghai" );
				require_once ('application/libraries/class.phpmailer.php');
				include ("application/libraries/class.smtp.php");
				$mail = new PHPMailer ();
				$mail->CharSet = "UTF-8";
				$mail->IsSMTP ();
				$mail->SMTPDebug = 1;
				$mail->SMTPAuth = true;
				$mail->SMTPSecure = "";
				$mail->Host = "1.1.2.5";
				$mail->Port = 25;
				$mail->Username = "nsdkj@nsdkj.com.cn";
				$mail->Password = "nsdkj101010";
				$mail->SetFrom ( 'nsdkj@nsdkj.com.cn', '纽斯达' );
				$mail->Subject = "来自纽斯达的密码找回邮件";
				$mail->AltBody = "请使用HTML方式查看邮件";
				$mail->MsgHTML ( $resetMsg );
				$mail->AddAddress ( $this->input->post ( 'email' ), $user ['name'] );
				if (! $mail->Send ()) {
					$data ['msg'] = 'mailFail';
					$data ['errMsg'] = "Mailer Error: " . $mail->ErrorInfo;
				} else {
					$data ['msg'] = "mailSuccess";
				}
			} else {
				$data ['msg'] = "forgetErr";
			}
			
			$this->load->view ( 'message', $data );
		}
	}
	
	function resetPwd() {
		$code = $this->uri->segment ( 3, 0 );
		$this->load->model ( 'Muser' );
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		if ($code == '0') {
			$data ['msg'] = 'reset_url_F';
			$this->load->view ( 'message', $data );
		} else {
			$id = substr ( $code, 0, strrpos ( $code, '_' ) );
			$num = substr ( $code, strrpos ( $code, '_' ) + 1 );
			
			if ($this->Muser->checkReset ( $id, $num )) {
				$this->form_validation->set_rules ( 'password', '新密码', 'trim|required|min_length[6]|max_length[15]' );
				$this->form_validation->set_rules ( 'rePassword', '重复密码', 'trim|required|min_length[6]|max_length[15]|callback_checkPwdCB' );
				if ($this->form_validation->run () == FALSE) {
					$data ['form'] = array ('id' => 'resetPwdForm' );
					$data ['code'] = $code;
					$this->load->view ( 'user_resetPwd', $data );
				} else {
					if ($this->Muser->resetPwd ( $id, $num, MD5 ( $this->input->post ( 'password' ) ) )) {
						$data ['msg'] = 'reset_T';
					} else
						$data ['msg'] = 'reset_F';
					$this->load->view ( 'message', $data );
				}
			} else {
				$data ['msg'] = 'reset_url_F';
				$this->load->view ( 'message', $data );
			}
		}
	}
	
	function modify() {
		$id = $this->session->userdata ( 'uid' );
		$data ['uid'] = $id;
		
		$this->load->model ( 'Mabout' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$this->load->helper ( 'form' );
		$this->load->model ( 'Muser' );
		if ($id) {
			$this->form_validation->set_rules ( 'oldPassword', '原密码', 'trim|min_length[6]|max_length[15]|callback_checkOldPwdCB' );
			$this->form_validation->set_rules ( 'password', '新密码', 'trim|min_length[6]|max_length[15]' );
			$this->form_validation->set_rules ( 'rePassword', '确认密码', 'trim|min_length[6]|max_length[15]|callback_checkPwdCB' );
			$this->form_validation->set_rules ( 'name', '姓名', 'trim|required|min_length[2]|max_length[10]' );
			$this->form_validation->set_rules ( 'mobile', '手机', 'trim|required|min_length[4]|max_length[20]|callback_checkPhoneCB' );
			$this->form_validation->set_rules ( 'test', '验证码', 'trim|required|callback_checkCaptchaCB' );
			
			if ($this->form_validation->run () == FALSE) {
				$tmp = $this->Muser->getUserbyId ( $id );
				$data ['name'] = $tmp ['name'];
				$data ['mobile'] = $tmp ['mobile'];
				$data ['img'] = $this->getCaptcha ();
				$data ['form'] = array ('id' => 'modifyForm' );
				$this->load->view ( 'user_modification', $data );
			} else {
				$query ['mobile'] = $this->input->post ( 'mobile' );
				$query ['name'] = $this->input->post ( 'name' );
				
				if ($data ['uid']) {
					$query2 = $this->Muser->getUserbyId ( $data ['uid'] );
					$data ['name'] = $query2 ['name'];
				}
				if (($this->input->post ( 'oldPassword' ) != '') && ($this->input->post ( 'password' ) != '')) {
					$query ['password'] = md5 ( $this->input->post ( 'password' ) );
				}
				
				if ($this->Muser->modification ( $query, $id )) {
					$data ['msg'] = 'modify_T';
					$this->load->view ( 'message', $data );
				} else {
					$data ['msg'] = 'modify_F';
					$this->load->view ( 'message', $data );
				}
			}
		
		} else {
			$data ['msg'] = 'login';
			$data ['url'] = base_url () . 'user/login';
			$this->load->view ( 'redirect', $data );
		}
	}
	
	function register() {
		$this->load->helper ( 'form' );
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$this->form_validation->set_rules ( 'email', '邮箱', 'trim|required|valid_email|max_length[40]|callback_checkEmailCB' );
		$this->form_validation->set_rules ( 'password', '登录密码', 'trim|required|min_length[6]|max_length[15]' );
		$this->form_validation->set_rules ( 'rePassword', '确认密码', 'trim|required|min_length[6]|max_length[15]|callback_checkPwdCB' );
		$this->form_validation->set_rules ( 'name', '姓名', 'trim|required|min_length[2]|max_length[10]' );
		$this->form_validation->set_rules ( 'mobile', '手机', 'trim|required|min_length[4]|max_length[20]|callback_checkPhoneCB' );
		$this->form_validation->set_rules ( 'test', '验证码', 'trim|required|callback_checkCaptchaCB' );
		
		if ($this->form_validation->run () == FALSE) {
			$data ['img'] = $this->getCaptcha ();
			$data ['form'] = array ('id' => 'registerForm' );
			$this->load->view ( 'user_register', $data );
		} else {
			$this->load->model ( 'Muser' );
			$dataDB = array ('email' => $this->input->post ( 'email' ), 'password' => md5 ( $this->input->post ( 'password' ) ), 'name' => $this->input->post ( 'name' ), 'mobile' => $this->input->post ( 'mobile' ), 'creatTime' => date ( "Y/m/d H:i:s", time () ), 'loginTime' => date ( "Y/m/d H:i:s", time () ), 'loginIp' => $this->input->ip_address (), 'activation' => random_string ( 'alnum', 15 ), 'reset' => '#' );
			$id = $this->Muser->addUser ( $dataDB );
			$activeMsg = "
						<p>亲爱的纽斯达用户，您好！</p>
						<p>&nbsp;</p>
						<p>欢迎您注册www.nsdkj.com.cn。</p>
						<p>这是一封来自纽斯达的注册确认信，请尽快点击下面的链接地址，激活账号完成注册：</p>
						<p><a href=\"" . base_url () . "user/activation/$id" . "_" . $dataDB ['activation'] . "/\">" . base_url () . "user/activation/$id" . "_" . $dataDB ['activation'] . "/</a></p>
						<p>（如果您无法点击此链接，请将上面的链接地址复制到您的浏览器地址栏中，打开页面即可）</p>
						<p>&nbsp;</p>
						<p>这是一封系统邮件，请勿回复</p>
						<p>&nbsp;</p>
						<p>上海纽斯达科技有限公司</p>
						<p>http://www.nsdkj.com.cn</p>
						<p>客服信箱：nsdkj@nsdkj.com.cn</p>
						<p>热线电话：021-63831111</p>
						";
			
			/*
			 * 邮箱：nsdkj@nsdkj.com.cn 密码：nsdkj101010 POP3:pop3.nsdkj.com.cn
			 * SMTP:smtp.nsdkj.com.cn
			 */
			if ($id) {
				error_reporting ( E_STRICT );
				date_default_timezone_set ( "Asia/Shanghai" );
				require_once ('application/libraries/class.phpmailer.php');
				include ("application/libraries/class.smtp.php");
				$mail = new PHPMailer ();
				$mail->CharSet = "UTF-8";
				$mail->IsSMTP ();
				$mail->SMTPDebug = 1;
				$mail->SMTPAuth = true;
				$mail->SMTPSecure = "";
				$mail->Host = "1.1.2.5";
				$mail->Port = 25;
				$mail->Username = "nsdkj@nsdkj.com.cn";
				$mail->Password = "nsdkj101010";
				$mail->SetFrom ( 'nsdkj@nsdkj.com.cn', '纽斯达' );
				// $mail->AddReplyTo ( "邮件回复地址,如admin#jiucool.com #换成@",
				// "邮件回复人的名称" );
				$mail->Subject = "来自纽斯达的注册确认邮件";
				$mail->AltBody = "请使用HTML方式查看邮件!";
				$mail->MsgHTML ( $activeMsg );
				$mail->AddAddress ( $dataDB ['email'], $dataDB ['name'] );
				// $mail->AddAttachment("images/phpmailer.gif"); // attachment
				// $mail->AddAttachment("images/phpmailer_mini.gif"); //
				// attachment
				if (! $mail->Send ()) {
					$data ['msg'] = 'mailFail';
					$data ['errMsg'] = "Mailer Error: " . $mail->ErrorInfo;
				} else {
					$data ['msg'] = "register_T";
				}
			} else {
				$data ['msg'] = "register_F";
			}
			
			$this->load->view ( 'message', $data );
		}
	}
	
	function activation() {
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$code = $this->uri->segment ( 3, 0 );
		if ($code == '0') {
			$data ['msg'] = 'activation_num_F';
		} else {
			$id = substr ( $code, 0, strrpos ( $code, '_' ) );
			$num = substr ( $code, strrpos ( $code, '_' ) + 1 );
			$this->load->model ( 'Muser' );
			if ($this->Muser->active ( $id, $num )) {
				$data ['msg'] = 'activation_T';
			} else
				$data ['msg'] = 'activation_F';
		}
		$this->load->view ( 'message', $data );
	}
	
	function waitActivation() {
		$this->load->model ( 'Mabout' );
		$data ['uid'] = $this->session->userdata ( 'uid' );
		$data ['name'] = $this->session->userdata ( 'uname' );
		$data ['cardAboutList'] = $this->Mabout->getAboutListbyClass ( 'C' );
		$data ['aboutList'] = $this->Mabout->getAboutListbyClass ( 'A' );
		
		$uid = $this->uri->segment ( 3, 0 );
		$this->load->model ( 'Muser' );
		$act = $this->Muser->getActivation ( $uid );
		if ($act) {
			if ($act ['activation'] == '#') {
				$data ['msg'] = 'activationed';
				$this->load->view ( 'message', $data );
			} else {
				$this->form_validation->set_rules ( 'test', '验证码', 'trim|required|callback_checkCaptchaCB' );
				if ($this->form_validation->run () == FALSE) {
					$data ['msg'] = '您的账户尚未激活，请至您的邮箱查收注册激活邮件并激活您的账号！';
					$data ['link'] = 'user/waitActivation/' . $uid;
					$data ['form'] = array ('id' => 'reActForm' );
					$data ['img'] = $this->getCaptcha ();
					$this->load->view ( 'user_waitActivation', $data );
				} else {
					$activeMsg = "
								<p>亲爱的纽斯达用户，您好！</p>
								<p>&nbsp;</p>
								<p>欢迎您注册www.nsdkj.com.cn。</p>
								<p>这是一封来自纽斯达的注册确认信，请尽快点击下面的链接地址，激活账号完成注册：</p>
								<p><p><a href=\"" . base_url () . "user/activation/$uid" . "_" . $act ['activation'] . "/\">" . base_url () . "user/activation/$uid" . "_" . $act ['activation'] . "/</a></p>
								<p>（如果您无法点击此链接，请将上面的链接地址复制到您的浏览器地址栏中，打开页面即可）</p>
								<p>&nbsp;</p>
								<p>这是一封系统邮件，请勿回复</p>
								<p>&nbsp;</p>
								<p>上海纽斯达科技有限公司</p>
								<p>http://www.nsdkj.com.cn</p>
								<p>客服信箱：nsdkj@nsdkj.com.cn</p>
								<p>热线电话：021-63831111</p>
								";
					
					error_reporting ( E_STRICT );
					date_default_timezone_set ( "Asia/Shanghai" );
					require_once ('application/libraries/class.phpmailer.php');
					include ("application/libraries/class.smtp.php");
					$mail = new PHPMailer ();
					$mail->CharSet = "UTF-8";
					$mail->IsSMTP ();
					$mail->SMTPDebug = 1;
					$mail->SMTPAuth = true;
					$mail->SMTPSecure = "";
					$mail->Host = "1.1.2.5";
					$mail->Port = 25;
					$mail->Username = "nsdkj@nsdkj.com.cn";
					$mail->Password = "nsdkj101010";
					$mail->SetFrom ( 'nsdkj@nsdkj.com.cn', '纽斯达' );
					$mail->Subject = "来自纽斯达的注册确认邮件";
					$mail->AltBody = "请使用HTML方式查看邮件";
					$mail->MsgHTML ( $activeMsg );
					$mail->AddAddress ( $act ['email'], $act ['name'] );
					if (! $mail->Send ()) {
						$data ['msg'] = 'mailFail';
						$data ['errMsg'] = "Mailer Error: " . $mail->ErrorInfo;
					} else {
						$data ['msg'] = "activation_mail_T";
					}
					$this->load->view ( 'message', $data );
				}
			}
		} else {
			$data ['msg'] = 'no_user';
			$this->load->view ( 'message', $data );
		}
	}
	
	// 功能函数
	function getCaptcha() {
		$this->load->helper ( 'captcha' );
		$this->load->helper ( 'string' );
		$vals = array ('word' => random_string ( 'numeric', 5 ), 'img_path' => './captchas/', 'img_url' => base_url () . 'captchas/', 'img_width' => 60, 'img_height' => 30, 'expiration' => 120 );
		$cap = create_captcha ( $vals );
		$this->session->set_userdata ( 'verifyCode', $cap ['word'] );
		return $cap ['image'];
	}
	
	function checkPwdCB($str) {
		if ($str == $this->input->post ( 'password' ))
			return TRUE;
		else {
			$this->form_validation->set_message ( 'checkPwdCB', '两次密码输入必须一致' );
			return FALSE;
		}
	}
	
	function checkOldPwdCB($str) {
		if ($str == '')
			return TRUE;
		else {
			$this->load->model ( 'Muser' );
			if ($this->Muser->checkPwdbyId ( md5 ( $str ), $this->session->userdata ( 'uid' ) ))
				return TRUE;
			else {
				$this->form_validation->set_message ( 'checkOldPwdCB', '%s错误' );
				return FALSE;
			}
		}
	}
	
	function checkEmailCB($str) {
		$this->load->model ( 'Muser' );
		if ($this->Muser->checkEmail ( $str ))
			return TRUE;
		else {
			$this->form_validation->set_message ( 'checkEmailCB', '%s已存在' );
			return FALSE;
		}
	}
	
	function checkEmail2CB($str) {
		$this->load->model ( 'Muser' );
		if ($this->Muser->checkEmail ( $str )) {
			$this->form_validation->set_message ( 'checkEmail2CB', '%s不存在' );
			return FALSE;
		} else {
			return TRUE;
		}
	}
	
	function checkEmail() {
		$email = $this->input->get ( 'email' );
		$data ['ret'] = 0;
		if ($email) {
			$this->load->model ( 'Muser' );
			if ($this->Muser->checkEmail ( $email ))
				$data ['ret'] = 1;
		}
		echo json_encode ( $data );
	}
	
	function checkCaptchaCB($str) {
		if (strcasecmp ( $str, $this->session->userdata ( 'verifyCode' ) ) == 0) {
			return TRUE;
		} else {
			$this->form_validation->set_message ( 'checkCaptchaCB', '%s不正确' );
			return FALSE;
		}
	}
	
	function checkCaptcha() {
		$word = $this->input->get ( 'word' );
		$data ['ret'] = 0;
		$data ['img'] = "";
		if (strcasecmp ( $word, $this->session->userdata ( 'verifyCode' ) ) == 0) {
			$data ['ret'] = 1;
		} else {
			$data ['img'] = $this->getCaptcha ();
		}
		echo json_encode ( $data );
	}
	
	function resetCaptcha() {
		$data ['image'] = $this->getCaptcha ();
		echo json_encode ( $data );
	}
	
	function checkPhoneCB($str) {
		if (preg_match ( "/^[0-9-]{8,20}$/", $str ))
			return TRUE;
		else {
			$this->form_validation->set_message ( 'checkPhoneCB', '%s不正确' );
			return FALSE;
		}
	}
}